package org.oexam.ostudy.serv;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oexam.ostudy.facade.ManageTestsPages;
import org.oexam.ostudy.facade.struct.LoggedUserDetails;
import org.oexam.ostudy.facade.struct.TestDisplayDetails;

/**
 * Servlet implementation class StartTest
 */
@WebServlet("/StartTest")
public class StartTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public StartTest() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		LoggedUserDetails details = (LoggedUserDetails) request.getSession()
				.getAttribute("userLoginDetails");

		if (details == null) {
			response.sendRedirect("Login.jsp");
		}
		if (details.isAuthenticated() && (details.getUserType() == 2)) {

			int testID = Integer.parseInt(request.getParameter("selectedTest"));
			int userID = details.getUserID();
			TestDisplayDetails testDisplayDetails = new TestDisplayDetails();
			try {
				testDisplayDetails = new ManageTestsPages()
						.startTestAndGetTestData(testID, userID);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				PrintWriter out = response.getWriter();

			    out.println("Student Has already taken this test");
			    out.close();
				
			}
			request.getSession().setAttribute("testData", testDisplayDetails);
			response.sendRedirect("Test");

		}
	}

}
